package com.atguigu.gmall.order.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/api/order/auth")
@SuppressWarnings("all")
public class OrderApiController {


    @Autowired
    private OrderService orderService;
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor executor;




    /**
     * api/order/auth/{page}/{limit}
     * 我的订单
     * @param page
     * @param limit
     * @return
     * 查询涉及到几张表：
     *
     *
     *
     */
    @GetMapping("/{page}/{limit}")
    public Result getOrderPageList(@PathVariable Long page,
                                   @PathVariable Long limit,
                                   HttpServletRequest request){

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //封装查询对象
        Page<OrderInfo> orderInfoPage=new Page<>(page,limit);
        IPage<OrderInfo> infoIPage=orderService.getOrderPageList(orderInfoPage,userId);

        return Result.ok(infoIPage);
    }


    /**
     * api/order/auth/submitOrder
     * 提交订单
     * @return
     */
    @PostMapping("/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);

        //获取流水号
        String tradeNo = request.getParameter("tradeNo");
        //校验流水号
        if(StringUtils.isEmpty(tradeNo) ||  !orderService.checkTradeCode(userId,tradeNo)){

            //错误
            return Result.fail().message("不能重复提交！！！");

        }
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //创建异步对象收集集合
        List<CompletableFuture> completableFutureList=new ArrayList<>();
        //创建异常结果收集集合
        List<String > errorList=new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {


            CompletableFuture<Void> chechStockFuture = CompletableFuture.runAsync(() -> {
                //校验库存
                boolean flag=orderService.chechStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
                //判断
                if(!flag){

                    errorList.add(orderDetail.getSkuId()+":"+orderDetail.getSkuName()+",库存不足！！");

                }

            }, executor);
            completableFutureList.add(chechStockFuture);




            //校验价格
            //获取实时价格
            CompletableFuture<Void> checkeSkuPriceFuture = CompletableFuture.runAsync(() -> {

                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                //比较
                if(orderDetail.getOrderPrice().compareTo(skuPrice)!=0){

                    //更改数据
                    //获取选中的商品清单--只是对已经获取商品清单进行更新价格，并没有保存到redis
                    List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.parseLong(userId));
                    //更新redis中的价格
                    cartCheckedList.stream().forEach(cartInfo -> {

                        //更新redis中已经选中商品
                        redisTemplate.opsForHash().put(
                                RedisConst.USER_KEY_PREFIX+userId+RedisConst.USER_CART_KEY_SUFFIX,
                                orderDetail.getSkuId().toString(),
                                cartInfo);


                    });


                   errorList.add(orderDetail.getSkuId()+":"+orderDetail.getSkuName()+",价格有变动！！");

                }
            }, executor);
            completableFutureList.add(checkeSkuPriceFuture);


        }
        //设置为一组异步and
        CompletableFuture.allOf(
                completableFutureList.toArray(new CompletableFuture[completableFutureList.size()])).join();

        //处理
        if(!CollectionUtils.isEmpty(errorList)){

            //import com.alibaba.nacos.common.utils.StringUtils;
            return Result.fail().message(StringUtils.join(errorList,","));

        }



        //设置用户id
        orderInfo.setUserId(Long.valueOf(userId));
        Long orderId= orderService.submitOrder(orderInfo);

        //删除流水号
        orderService.deleteTradeNo(userId);



        return Result.ok(orderId);
    }



    /**
     * /api/order/auth/trade
     * 去结算
     * @return
     */
        @GetMapping("/trade")
        public Result trade(HttpServletRequest request){

            //获取用户id
            String userId = AuthContextHolder.getUserId(request);

            Map<String,Object> resultMap=new HashMap<>();


            //获取用户地址列表 userAddressList
            List<UserAddress> userAddressListByUserId = userFeignClient.findUserAddressListByUserId(Long.valueOf(userId));
            resultMap.put("userAddressList",userAddressListByUserId);
            //获取用户选中的商品清单 detailArrayList
            List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.parseLong(userId));

            //将购物项信息装换到订单项
            if(!CollectionUtils.isEmpty(cartCheckedList)){

                List<OrderDetail> orderDetailList=new ArrayList<>();
                for (CartInfo cartInfo : cartCheckedList) {

                    //创建订单项
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setSkuId(cartInfo.getSkuId());
                    orderDetail.setSkuName(cartInfo.getSkuName());
                    orderDetail.setImgUrl(cartInfo.getImgUrl());
                    orderDetail.setSkuNum(cartInfo.getSkuNum());
                    orderDetail.setOrderPrice(productFeignClient.getSkuPrice(cartInfo.getSkuId()));
                    orderDetailList.add(orderDetail);
                }

                resultMap.put("detailArrayList",orderDetailList);

                //总数量totalNum
                resultMap.put("totalNum",orderDetailList.size());

                //总金额totalAmount
                OrderInfo orderInfo=new OrderInfo();
                orderInfo.setOrderDetailList(orderDetailList);
                orderInfo.sumTotalAmount();

                BigDecimal totalAmount = orderInfo.getTotalAmount();
                resultMap.put("totalAmount",totalAmount);

            }
            //响应流水号到页面
            resultMap.put("tradeNo",orderService.getTradeNo(userId));







            return Result.ok(resultMap);
    }
}
